package cn.yzx.pethome.system.logininfo.service.impl;

import cn.yzx.pethome.system.logininfo.domain.LoginRo;
import cn.yzx.pethome.system.logininfo.domain.LoginVo;
import cn.yzx.pethome.system.logininfo.domain.Logininfo;
import cn.yzx.pethome.system.logininfo.mapper.LogininfoMapper;
import cn.yzx.pethome.system.logininfo.service.ILogininfoService;
import cn.yzx.pethome.base.service.impl.BaseServiceImpl;
import cn.yzx.pethome.system.role.mapper.RoleMapper;
import cn.yzx.pethome.system.user.service.IEmployeeService;
import cn.yzx.pethome.utils.AjaxResult;
import cn.yzx.pethome.utils.BusinessException;
import cn.yzx.pethome.utils.MD5Utils;
import cn.yzx.pethome.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yanzixuan
 * @since 2023-01-16
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public AjaxResult account(LoginRo login) {
        if(login.getType() == null){
            throw new BusinessException("非法访问！");
        }
        if(login.getPassword() == null || "".equals(login.getPassword().trim())){
            throw new BusinessException("密码不能为空！");
        }
        if(login.getUsername() == null || "".equals(login.getUsername().trim())){
            throw new BusinessException("用户名不能为空！");
        }
        Logininfo account = logininfoMapper.account(login);
        if(account == null){
            throw new BusinessException("用户名或者密码错误！");
        }

        if(login.getAutoLogin()){
            String password = login.getPassword();
            String salt = account.getSalt();
            String s = MD5Utils.encrypByMd5(password+salt);
            if(!account.getPassword().equals(s)){
                throw new BusinessException("密码错误！");
            }
        }

        //128位的随机数
        String token = StrUtils.getComplexRandomString(128);
        redisTemplate.opsForValue().set(token,account,30, TimeUnit.MINUTES);

        Long empId = employeeService.findByLogininfoId(account.getId()).getId();//根据LogininfoId查询员工id
        List<Long> roles = employeeService.findRoleByEmpId(empId);//获取到自己的角色

        List<String> permissionsByRoleIds = roleMapper.getPermissionsByRoleId(roles);//自己的权限
        redisTemplate.opsForValue().set(token+"permission",permissionsByRoleIds,30, TimeUnit.MINUTES);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setLogininfo(account);
        return AjaxResult.success().setData(loginVo).setMsg("managerLogin");
    }
}
